package com.shortchainsystem.link.controller;

import com.shortchainsystem.link.service.LinkService;
import com.shortchainsystem.model.base.Result;
import com.shortchainsystem.model.domain.link.DTO.LinkIdsDto;
import com.shortchainsystem.model.domain.link.Link;
import com.shortchainsystem.model.domain.link.DO.LinkDO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.view.RedirectView;

import javax.servlet.http.HttpServletRequest;


@RestController
@Slf4j
public class LinkController {
    @Autowired
    private LinkService linkService;

    /**
     *   一次生成短链
     */
    @PostMapping("/singleGenerate")
    public Result singleGenerate(@RequestBody LinkDO linkDto){
        return linkService.encode(linkDto);
    }

    /**
     *   批量生成短链
     */
    @PostMapping("/batchGenerate")
    public Result batchGenerate(@RequestBody LinkDO linkDto){
        return linkService.batchEncode(linkDto);
    }

    /**
     *    访问短链
     */
    @GetMapping("/{shortUrl}")
    public ModelAndView access(@PathVariable("shortUrl") String shortUrl, HttpServletRequest request, Model model){
        try {
            String longUrl = linkService.decode(shortUrl,request);
            return new ModelAndView(new RedirectView(longUrl));
        } catch (Exception e) {
            model.addAttribute("errorMessage", "该页面不存在！");
            return new ModelAndView("sorry");
        }
    }

    @GetMapping("/sorry")
    public String sorry() {
        return "抱歉，未找到页面！";
    }

    /**
     *   查看短链信息
     */
    @PostMapping("/info")
    public Result getInfo(@RequestParam("shortUrl") String shortUrl){
        return linkService.getInfo(shortUrl);
    }

    /**
     *    编辑短链
     */
    @PutMapping("/edit")
    public Result edit(@RequestBody LinkDO linkDO){
        return linkService.edit(linkDO);
    }

    /**
     *   批量删除短链
     */
    @DeleteMapping("/batchDelete")
    public Result batchDelete(@RequestBody LinkIdsDto linkIdsDto){
        return linkService.batchDelete(linkIdsDto);
    }
}